package com.map.lbs.http;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import android.util.Log;

public class ApiClient {
	private static String cookies = null;
	private HttpURLConnection conn;
	private final int DEFAULT_HTTP_TIMEOUT = 30000; //5m
	
	public ApiClient(String url){
		try {
			URL httpUrl = new URL(url);
			conn = (HttpURLConnection) httpUrl.openConnection(); 
			
			if(cookies != null){
				conn.setRequestProperty("Cookie", cookies);
			}
			
			conn.setConnectTimeout(DEFAULT_HTTP_TIMEOUT);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setDefaultUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setInstanceFollowRedirects(true);
			conn.setRequestProperty("Charset", "UTF-8");
		} catch (Exception e) {
			Log.e(ApiClient.class.getName(), "Http URL error.", e);
			conn = null;
		}
	}
	
	public void postData(Map<String,Object> params, PostDataSuccessEvent onSuccess, PostDataFailedEvent onFailed){
		if(conn != null){
			DataOutputStream os = null;
			InputStream is = null;
			try {
				StringBuffer content = new StringBuffer();
				boolean first = true;
				for(String key : params.keySet()){
					if(!first){
						content.append("&");
					}else{
						first = false;
					}
					content.append(key).append("=").append(URLEncoder.encode(params.get(key).toString(), "UTF-8"));
				}
				Log.d(ApiClient.class.getName(), content.toString());
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				conn.setRequestProperty("Content-Length", String.valueOf(content.length()));
				
				conn.connect();
				
				//get Cookie
				if(cookies == null){
					List<String> cookieList = ((Map<String, List<String>>)conn.getHeaderFields()).get("Set-Cookie");
					if(cookieList != null){
						for(String str : cookieList) {
						    cookies += str + "; ";
						}
					}
				}
				
				os = new DataOutputStream(conn.getOutputStream());
				os.writeBytes(content.toString());
				os.flush();
				
				int responseCode = conn.getResponseCode();
				if(responseCode == HttpURLConnection.HTTP_OK){
					if(onSuccess != null){
						is = conn.getInputStream();
						onSuccess.handleResponse(is);
					}
				}else{
					Log.w(ApiClient.class.getName(), "Http status error: " + responseCode);
					if(onFailed != null){
						onFailed.handleFailure(responseCode);
					}
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(os != null){
					try {
						os.close();
					} catch (IOException e) {
					}
				}
				
				if(is != null){
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
		}
	}
	
	//Use this function to upload file, the file size should not be more than 4M
	public boolean uploadFile(File file, String contentType){
		if(conn != null){
			DataOutputStream os = null;
			FileInputStream is = null;
			try {
				conn.setRequestProperty("Content-Length", String.valueOf(file.length()));
				conn.setRequestProperty("Content-Type", contentType);
				
				conn.connect();
				is = new FileInputStream(file);
				os = new DataOutputStream(conn.getOutputStream());
				
				byte[] buffer = new byte[4096];
				int readCount = is.read(buffer);
				
				while(readCount > 0){
					os.write(buffer, 0, readCount);
					readCount = is.read(buffer);
				}
				os.flush();
				int responseCode = conn.getResponseCode();
				if(responseCode == HttpURLConnection.HTTP_OK){
					return true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				if(os != null){
					try {
						os.close();
					} catch (IOException e) {
					}
				}
				
				if(is != null){
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
		}
		return false;
	}
}
